import django_filters
from goods.models import *
from django.db.models import Q


# 商品过滤类
class GoodsFilter(django_filters.rest_framework.FilterSet):

    pricemin = django_filters.NumberFilter(field_name='shop_price', lookup_expr='gte')
    pricemax = django_filters.NumberFilter(field_name='shop_price', lookup_expr='lte')

    # 自定义过滤器，根据分类过滤商品
    top_category = django_filters.NumberFilter(method='top_category_filter')

    # 获取的是1级分类下的所有商品，4个默认参数
    def top_category_filter(self, queryset, name, value):
        # 前端传来的value是一级分类的id
        # 但是商品的外键关联到的分类，有可能是一级，二级或者三级分类
        return queryset.filter(Q(category_id=value) |
                                Q(category__parent_category_id=value) |
                                Q(category__parent_category__parent_category_id=value))

    class Meta:
        model = Goods
        fields = ('pricemin', 'pricemax', 'is_hot', 'is_new')




